"""
    PartnerGate application
    Handles events used for PartnerGate url management
    (ex" /partner_id/url?callback=func)
"""
from flask import Flask, g, Blueprint, request, make_response
from decorators import gate_response
from models import DataAccess

pgate = Blueprint('pgate', __name__)


@pgate.route("/<int:partner_id>/<md5:url>", methods=['GET'], strict_slashes=False)
@gate_response(expires="+7d", max_age=604800)
def access(partner_id, url):
    """Returns the date the url was first seen.
       If a queryparameter named 'callback' exists, will wrap
       the response in a function with query string value.

       Examples:
         1. http://buzzfeed/50005/e018e2d49783e212c38c33f69fed6c01?callback=a
           => a(1313523773), 200 OK
         2. http://buzzfeed/50005/e018e2d49783e212c38c33f69fed6c01
           => 1313523773, 200 OK
         3. http://buzzfeed/50005/e018e2d49783e212c38c33f69fed6c01/
           => 1313523773, 200 OK"""
    first_seen = 0
    first_seen = g.db.get_url(partner_id, url)
    if first_seen <= 0:
        first_seen = g.db.add_url(partner_id, url)	

    resp = str(first_seen)

    # move to decorator function
    callback = request.args.get("callback")
    if callback:
        resp = "%s(%s);\n" % (callback, resp)

    return resp

@pgate.before_request
def before_request():
    """Make sure we have access to the datamodel before each request."""
    g.db = DataAccess()

@pgate.after_request
def after_request(response):
    """Make sure we cleanup after each request."""
    g.db.close()
    return response